package handle

import (
	"git.oschina.net/cnjack/z_app_server/model"
	"git.oschina.net/cnjack/z_app_server/tool"
	"github.com/go-martini/martini"
	"github.com/martini-contrib/render"
	"net/http"
	"strconv"
	"time"
)

var memberModel model.Member
var messageModel model.Message
var relationModel model.Relationship
var messageTimeInfo model.User_message_info

func CheckUser(resp http.ResponseWriter, req *http.Request, r render.Render, c martini.Context) {
	var err error
	req.ParseForm()
	var user = req.PostFormValue("user")
	var token = req.PostFormValue("token")
	var token_time = req.PostFormValue("token_time")
	token_time_int, err := strconv.Atoi(token_time)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "token is error",
		})
		return
	}
	var TokenTime_int = int(time.Now().Unix())
	var TokenTime = strconv.Itoa(TokenTime_int)
	//超过7天认为已经退出
	if (TokenTime_int - token_time_int) > 7*24*60*60 {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "the token is die",
		})
		return
	}
	if user == "" || token == "" || token_time == "" {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "param is epmty",
		})
		return
	}
	memberInfo, err := memberModel.FindOne(user)
	if err != nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": err.Error(),
		})
		return
	}
	if memberInfo == nil {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "user is not exist",
		})
		return
	}

	aesEnc := tool.AesEncrypt{Key: "435nvyw8nc8nycn34ynci8ycn5gyc983"}
	token_s := aesEnc.Decrypt(token)
	var token_c = user + memberInfo.Pass + token_time
	if token_s != token_c {
		r.JSON(200, map[string]interface{}{
			"code": "1",
			"info": "token is error",
		})
		return
	}

	//大于30分钟重新生成token
	if (TokenTime_int - token_time_int) > 30*60 {
		token = aesEnc.Encrypt(user + memberInfo.Pass + TokenTime)
		if err != nil {
			r.JSON(200, map[string]interface{}{
				"code": "1",
				"info": err.Error(),
			})
			return
		}
		err = memberModel.UpdateToken(token, memberInfo.Id)
		if err != nil {
			r.JSON(200, map[string]interface{}{
				"code": "1",
				"info": err.Error(),
			})
			return
		}
		resp.Header().Add("Custom-Header", token+":"+TokenTime)
		//res.Header().Add("token", token)
		//res.Header().Add("token_time", TokenTime)
	}

	req.Header.Add("userid", strconv.Itoa(int(memberInfo.Id)))
	c.Next()
}
func AllowOriginHandle(resp http.ResponseWriter, c martini.Context) {
	resp.Header().Add("Access-Control-Allow-Origin", "*")
	resp.Header().Add("ccess-Control-Allow-Methods", "POST, GET")
	//resp.Header().Add("Custom-Header", "Own-Data")
	resp.Header().Add("Access-Control-Expose-Headers", "Custom-Header")
	c.Next()
}
